// mircoApp/gradevin/component/yz_optionShow.js
const app = getApp();
var specsManage = []; // 选择池 用于排序
var optionsId = ""; // 选择后的 规格ID
var optionsMaxCount = 1;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false,
    },
    goodsInfo: {
      type: Object,
      value: {},
    },
    carts: {
      type: Array,
      value: [],
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    optionsMaxCount: 1,
  },
  attached() {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en,
    });
  },
  observers: {
    "show,goodsInfo": function (isShow, info) {
      console.log(info);
      if (isShow) {
        this.initPopView(); // 初始化弹窗view
      }
    },
    "carts": function (cartList) {
      for (let i = 0; i < cartList.length; i++) {
        if (
          cartList[i].goods_id == this.data.goodsInfo.id &&
          cartList[i].option_id == optionsId
        ) {
          this.setData({
            popNum: cartList[i].total,
            popCard: cartList[i],
          });
          break;
        }
        this.setData({
          popNum: 0,
          popCard: {},
        });
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    changeAddCount(e) {
      let {
        id,
        num
      } = e.currentTarget.dataset;
      this.triggerEvent("cartChange", {
        id: id,
        num: num
      })
    },
    submitAction() {
      if (specsManage.length < this.data.goodsInfo.has_many_specs.length) {
        // 请选择规格
        this.close();
        wx.showToast({
          title: this.data.goodsDescription,
          icon: "none",
        });
        return;
      }
      this.triggerEvent("submitAction", {
        goods_id: this.data.goodsInfo.id,
        option_id: optionsId,
      });
    },
    close() {
      this.triggerEvent("closePopup");
    },
    // 初始化弹窗view
    initPopView() {
      console.log("dddddddddddddd");
      optionsId = "";
      specsManage = [];
      this.setData({
        specid: "",
        popNum: 0,
      });
      if (this.data.goodsInfo.has_option == 1) {
        // 是否有规格
        this.setData({
          popTitle: this.data.goodsInfo.title,
          popThumb: this.data.goodsInfo.thumb,
          popStock: this.data.goodsInfo.stock,
          popCard: {},
        });
        // 设置默认图片
        // 设置商品名
        // 设置默认库存
        if (!this.data.specid.length) {
          let popPrice =
            this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price; // 设置默认价格
          if (this.data.goodsInfo.point_goods) {
            popPrice =
              this.data.goodsInfo.point_goods.min_point +
              "-" +
              this.data.goodsInfo.point_goods.max_point; //设置默认价格
          }
          this.setData({
            popPrice: popPrice,
          });
        }
        this.setData({
          goodsDescription: "请选择",
        });
        let goodsDescription;
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          goodsDescription = this.data.goodsDescription;
          goodsDescription += "" + this.data.goodsInfo.has_many_specs[i].title;
        }
        this.setData({
          goodsDescription,
        });
        if (!this.data.optionsId) {
          // 默认选择第一个
          for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
            if (
              this.data.goodsInfo.goods_option_ids &&
              this.data.goodsInfo.goods_option_ids.length >= 0
            ) {
              for (
                let j = 0; j <
                this.data.goodsInfo.has_many_specs[i].has_many_specs_item
                .length; j++
              ) {
                if (
                  this.data.goodsInfo.has_many_specs[i].has_many_specs_item[j]
                  .id == Number(this.data.goodsInfo.goods_option_ids[i])
                ) {
                  this.selectSpecs(
                    this.data.goodsInfo.has_many_specs[i].has_many_specs_item[
                      j
                    ],
                    "first",
                    i
                  );
                }
              }
            } else {
              this.selectSpecs(
                this.data.goodsInfo.has_many_specs[i].has_many_specs_item[0],
                "first",
                i
              );
            }
          }
        }
      } else {
        console.log(
          this.data.goodsInfo,
          "dddddddddddddddddd2222222222222222222222"
        );
        this.setData({
          goodsDescription: "",
          optionsMaxCount: this.data.goodsInfo.stock,
        });
        // 设置最大购买量
      }
    },
    // 界面选择规格触发事件
    selectSpecs(e, str, i) {
      let data = {};
      let id = 0;

      if (str == "first") {
        data = e;
        id = e.id;
      } else {
        data = e.target.dataset.item || e.currentTarget.dataset.item;

        id = e.target.dataset.id || e.currentTarget.dataset.id;
      }

      // 处理选择池
      this.manageSpecs(data);

      // 处理规格组合选择状态
      this.setGoodsSpecs(data);

      // 设置选择规格后的 价格、照片、库存
      this.setGoodsSpecsChangeInfo(id);

      // 判断当前购买总量与库存的关系
      this.getMaxCount();
    },
    // 处理选择池
    manageSpecs(data) {
      var specsObject = {};
      specsObject.id = data.id;
      specsObject.specid = data.specid;
      specsObject.title = data.title;

      if (specsManage.length > 0) {
        for (let i = 0; i < specsManage.length; i++) {
          if (specsManage[i].specid == specsObject.specid) {
            specsManage.splice(i, 1);
          }
        }
        specsManage.push(specsObject);
      } else {
        specsManage.push(specsObject);
      }

      // 排序
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        var newSpecsManage = [];
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (
              this.data.goodsInfo.has_many_specs[i].id == specsManage[j].specid
            ) {
              newSpecsManage.push(specsManage[j]);
              break;
            }
          }
        }
        specsManage = newSpecsManage;
      }
      this.setGoodsDescription();
    },
    // 处理goodsDescription 数据
    setGoodsDescription() {
      var description = "";
      // 相等代表全选了 体现语句
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        description = "已选择 ";
        for (let i = 0; i < specsManage.length; i++) {
          description += specsManage[i].title + " ";
        }
        this.setData({
          goodsDescription: description,
        });
      } else {
        description = "请选择 ";

        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (
              this.data.goodsInfo.has_many_specs[i].id != specsManage[j].specid
            ) {
              description += this.data.goodsInfo.has_many_specs[i].title + " ";
              break;
            }
          }
        }
        this.setData({
          goodsDescription: description,
        });
      }
    },
    // 判断当前购买总量与库存的关系
    getMaxCount() {
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        if (optionsMaxCount == 0) {
          // 库存不足
          this.setData({
            popNum: 0,
          });
        }
        if (this.data.popNum > optionsMaxCount) {
          this.setData({
            popNum: optionsMaxCount,
          });
        }
      }
    },
    // 处理规格组合选择状态 过滤数据
    setGoodsSpecs(specs) {
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        if (specs.specid != this.data.goodsInfo.has_many_specs[i].id) {
          this.setGoodsSpecsStatus(
            this.data.goodsInfo.has_many_specs[i].has_many_specs_item,
            specs.id
          );
        }
      }
    },
    // 处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
    setGoodsSpecsStatus(specitem, id) {
      let options = []; // 数据池

      for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
        let _specs = this.data.goodsInfo.has_many_options[i].specs.split("_");
        // 判断是否包含
        for (let j = 0; j < _specs.length; j++) {
          if (_specs[j] == id) {
            options.push(this.data.goodsInfo.has_many_options[i]);
          }
        }
      }

      for (let m = 0; m < options.length; m++) {
        let _specs = options[m].specs.split("_");
        for (let y = 0; y < _specs.length; y++) {
          if (_specs[y] != id && options[m].stock == 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                specitem[n].c = true;
              }
            }
          } else if (_specs[y] != id && options[m].stock > 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                specitem[n].c = false;
              }
            }
          }
        }
      }
    },
    // 处理商品goodsSpecs 并排序 新方法
    setGoodsSpecsBySort(specs) {
      let _specs = specs.split("_"); // 先变成数组
      // _specs.sort();//排序
      _specs.sort(function (a, b) {
        return a - b;
      });

      // 在组装回去
      let goodsSpecs = "";
      for (let j = 0; j < _specs.length; j++) {
        goodsSpecs += _specs[j] + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); // 处理"_"

      return goodsSpecs;
    },
    // 设置选择规格后的 价格、照片、库存
    setGoodsSpecsChangeInfo(id) {
      let popPrice = "";
      // 根据ID 排序 specsManage.sort()
      specsManage.sort(function (a, b) {
        return a.id - b.id;
      });
      if (specsManage.length === this.data.goodsInfo.has_many_specs.length) {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); // 处理"_"
        this.setData({
          specid: goodsSpecs,
        });
        for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
          if (
            goodsSpecs ===
            this.setGoodsSpecsBySort(
              this.data.goodsInfo.has_many_options[i].specs
            )
          ) {
            if (this.data.goodsInfo.point_goods) {
              popPrice =
                this.data.goodsInfo.point_goods.point_option[i].goods_point; //设置默认价格
            } else {
              popPrice = this.data.goodsInfo.has_many_options[i].product_price; //设置默认价格
            }
            this.setData({
              popPrice: popPrice,
            });
            // 设置默认价格
            // 设置价格
            let popThumb = app._isTextEmpty(
                this.data.goodsInfo.has_many_options[i].thumb
              ) ?
              this.data.goodsInfo.thumb :
              this.data.goodsInfo.has_many_options[i].thumb; // 设置图片
            this.setData({
              popThumb,
              popStock: this.data.goodsInfo.has_many_options[i].stock,
            }); // 设置库存

            optionsId = this.data.goodsInfo.has_many_options[i].id; // 设置规格ID，用于生成订单
            optionsMaxCount = this.data.goodsInfo.has_many_options[i].stock; // 库存最大数 用于切换更改买家购买数量
            if (optionsMaxCount > 0) {
              this.setData({
                popNum: 0,
              });
            }
            if (this.data.isMultiSpecs) this.getMemberPrice(optionsId);
            break;
          }
        }

        for (let i = 0; i < this.data.carts.length; i++) {
          if (
            this.data.carts[i].goods_id == this.data.goodsInfo.id &&
            this.data.carts[i].option_id == optionsId
          ) {
            this.setData({
              popNum: this.data.carts[i].total,
              popCard: this.data.carts[i],
            });
            break;
          }
          this.setData({
            popNum: 0,
            popCard: {},
          });
        }
      } else {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        this.setData({
          specid: goodsSpecs,
        });
      }
    },
    getMemberPrice(_optionsId) {
      if (!_optionsId) return;
      let specsVIPPrc = 0;
      this.setData({
        specsVIPPrc,
      });
      let urlStr = app.getNetAddresss("goods.other-info.option-vpi-price");
      urlStr += "&option_id=" + _optionsId;
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            specsVIPPrc = res.data.vip_price || null;
          } else {
            specsVIPPrc = null;
          }
          this.setData({
            specsVIPPrc,
          });
        },
        fail: function (res) {
          specsVIPPrc = null;
          this.setData({
            specsVIPPrc,
          });
        },
      });
    },
  },
});